package com.xiaoq.logs.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoq.JWTTokenAuthenFilter;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.logs.entity.NginxLog;
import com.xiaoq.logs.service.NginxLogService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by chenjh on 2018/2/11.
 */
@Component
public class KafkaReceiver {

    private static final Logger LOGGER = LoggerFactory.getLogger(KafkaReceiver.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static Set<String> SET_FILTER = new HashSet<>();

    @Autowired
    private NginxLogService nginxLogService;

    @Autowired
    private IdGenerator idGenerator;


    static {
        SET_FILTER.add("https://sites.xiaoq.online/swagger-ui.html");
        SET_FILTER.add("https://matrix.xiaoq.online/swagger-ui.html");
        SET_FILTER.add("https://order.xiaoq.online/swagger-ui.html");
        SET_FILTER.add("https://user.xiaoq.online/swagger-ui.html");
        SET_FILTER.add("/api/v1/log");
    }


    @KafkaListener(topics = "${kafka.topic.boot}")
    public void receive(ConsumerRecord<String, String> consumerRecord) {
        if(consumerRecord!=null && StringUtils.isNotEmpty(consumerRecord.value())){
            String value = consumerRecord.value();
            try {
                NginxLog nginxLog = objectMapper.readValue(value, NginxLog.class);
                if(StringUtils.isNotEmpty(nginxLog.getRequest())){
                    String request = nginxLog.getRequest();
                    String[] requestArr = request.split(" ");
                    String requestMethod = requestArr[0];
                    String requestUrl = requestArr[1];
                    nginxLog.setRequestMethod(requestMethod);
                    nginxLog.setRequestUrl(requestUrl);

                    if(SET_FILTER.contains(requestUrl)){
                        return;
                    }

                    if(!requestUrl.startsWith("/api/v1")){
                        return;
                    }
                }

                if(nginxLog.getReferer()!=null && SET_FILTER.contains(nginxLog.getReferer())){
                    return;
                }

                if(nginxLog.getToken()!=null && nginxLog.getToken().startsWith("Bearer ")){
                    String access_token = nginxLog.getToken().substring(7);
                    Claims claims = Jwts.parser().setSigningKey(JWTTokenAuthenFilter.JWT_KEY).parseClaimsJws(access_token).getBody();
                    String userId = claims.get("userId").toString();
                    nginxLog.setUserId(userId);
                }

                nginxLog.setId(idGenerator.nextId());
                nginxLogService.save(nginxLog);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
